var keditor;
if(!jianyueMobileClient()) {
	KindEditor.ready(function (K) {
		keditor = K.create("#textarea", {themeType:"white", minHeight:"60px", height:"60px", items:[], newlineTag:"br", cssData:"body img{width:22px;}body{font-size:14px}", afterChange:function () {
			setTimeout("checkTextCount()", 5);
		}});
		tempEditorFrameBody = keditor.edit.iframe.get().contentWindow.document.body;
		$(tempEditorFrameBody).click(function () {
			try {
				stopTitle();
			}
			catch (err) {
			}
		});
		$(tempEditorFrameBody).bind("keydown", function (event) {
			if (event.ctrlKey && 13 === event.keyCode) {
			} else {
				if (13 == event.keyCode) {
					var textCount = keditor.count("text");
					if (textCount == 0) {
						setTimeout("editorEmpty()", 5);
					} else {
						sendChatMessage();
					}
				}
			}
		});
		$(tempEditorFrameBody).on("paste", function () {
			setTimeout(function () {
				var editorContent = keditor.html();
				keditor.html("");
				keditor.insertHtml(formatHtmlToText(editorContent));
			}, 3);
		});
		listentPaste();
	});
}
function checkTextCount() {
	var textCount = keditor.count("text");
	if (textCount > 0 && textCount <= 500) {
		$("#btnSend").addClass("active");
	} else {
		$("#btnSend").removeClass("active");
	}
}
document.onkeydown = keyDownSearch;
function keyDownSearch(e) {
	var theEvent = e || window.event;
	var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
	if (code == 13) {
		var textCount = keditor.count("text");
		if (textCount == 0) {
			setTimeout("editorEmpty()", 5);
		} else {
			var OneRequest = getCurrentRequest();
			sendMsg(OneRequest);
		}
		return false;
	}
	return true;
}
var urlReg = /(http:\/\/|https:\/\/)(\S+)/gi;
function formatHtmlToText(content) {
	var tempContent = $("<img>" + content + "<img>");
	var sendContent = "";
	for (var i = 1; i < tempContent.length - 1; i++) {
		if (tempContent[i].nodeName == "IMG") {
			sendContent += $.fn.parseWechat2(tempContent[i].alt);
		} else {
			if (tempContent[i].nodeName == "BR") {
				sendContent += "<br>";
			} else {
				if (tempContent[i].nodeName == "P" && tempContent[i].firstElementChild && tempContent[i].firstElementChild.nodeName == "BR") {
					sendContent += "\n";
				} else {
					if (tempContent[i]) {
						var subContet = "";
						if (tempContent[i].textContent) {
							subContet = tempContent[i].textContent;
						} else {
							if (tempContent[i].data) {
								subContet = tempContent[i].data;
							} else {
								if (tempContent[i].innerHTML) {
									subContet = tempContent[i].innerHTML;
								}
							}
						}
						if (subContet) {
							sendContent += subContet.replace(urlReg, "<a href=\"$1$2\" target=\"_blank\">$1$2</a>");
						}
					}
				}
			}
		}
	}
	return sendContent;
}
function listentPaste() {
	if (checkSupportFormData()) {
		keditor.edit.iframe.get().contentWindow.document.body.addEventListener("paste", function (event) {
			var userAgent = navigator.userAgent;
			if (userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") < 0) {
				return;
			}
			if (userAgent.indexOf("Opera") > -1 && userAgent.indexOf("Chrome") < 0) {
				return;
			}
			if (event.clipboardData || event.originalEvent) {
				var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
				if (clipboardData.items) {
				// for chrome
					var items = clipboardData.items, len = items.length, blob = null;
					for (var i = 0; i < len; i++) {
						if (items[i].type.indexOf("image") !== -1) {
							blob = items[i].getAsFile();
						}
					}
					if (blob !== null) {
						event.preventDefault();
						var reader = new FileReader();
						reader.onload = function (event) {
							var base64_str = event.target.result;
							showPastedImage(base64_str, "paste");
						};
						reader.readAsDataURL(blob);
					}
				} else {
				//for firefox
					setTimeout(function () {
						var imgList = optionsData.pasteTarget.querySelectorAll("img"), len = imgList.length, stream = "", i;
						if (len < 1) {
							return;
						}
						for (i = 0; i < len; i++) {
							if (imgList[i].className !== "my_img") {
								stream = imgList[i].src;
							}
						}
						showPastedImage(stream, "paste");
					}, 1);
				}
			} else {
		//for ie11
				setTimeout(function () {
					var imgList = optionsData.pasteTarget.querySelectorAll("img"), len = imgList.length, stream = "", i;
					if (len < 1) {
						return;
					}
					for (i = 0; i < len; i++) {
						if (imgList[i].className !== "my_img") {
							stream = imgList[i].src;
						}
					}
					if (stream.indexOf("http") < 0) {
						showPastedImage(stream, "paste");
					}
				}, 1);
			}
		});
	} else {
		$("#cutBtn").hide();
	}
	
	
	var showing = false;
	function showPastedImage(stream, type) {
		if (!showing) {
			showing = true;
			var panelArea = ["500px", "500px"];
			var w = $("#msgWrapper").width();
			if(w < 500) {
				panelArea = [(w - 60) + "px", (w - 60) + "px"];
			}			
			layer.open({
				type:1, 
				title:TEXT.SEND_IMAGE, 
				skin:"layui-layer-upload-img", 
				closeBtn:0, 
				shift:2, 
				shadeClose:false, 
				area:panelArea, 
				content:"<div class=\"html5-paste-upload-img-div\" style=\"width:" + panelArea[0] + ";height:" + (Number(panelArea[1].slice(0, -2)) - 100) + "px\"><img  id=\"pasteImage\" src=\"" + stream + "\"    /></div>", 
				btn:[TEXT.CANCEL, TEXT.VIEW_LARGER, TEXT.SEND], 
				cancel:function (index) {//VIEW LARGER PIC
					veiwLargerImage("pasteImage");
					showing = false;
					return false;
				}, btn3:function (index) {//CONFIRM TO SEND
					sendPastedImage(stream, type);
					showing = false;
					layer.close(index);
				}, yes:function (index, layero) {
					showing = false;
					layer.close(index);
				}}
			);
		}
	}
	function veiwLargerImage(id) {
		var remoteUrl = $("#" + id)[0].src;
		if (remoteUrl != '') {
			var imgWin = window.open('', '_blank');
			imgWin.document.write('<html><head>	<meta charset="UTF-8"><title>' +TEXT.VIEW_LARGER+ '</title></head><body><img src="' + remoteUrl + '"></img><body></html>');
			imgWin.document.close();
		}
	}
	
	function sendPastedImage(stream, type) {
		var formData = new FormData(); 
		formData.append("file", convertBase64UrlToBlob(stream)); 
		formData.append("bizType", "CHAT");
		formData.append("multiType", "IMG");
		try {
			if(crm) {//THE VISITOR
				formData.append("id", crm.id);
			}
		} catch(e) {
		}
		 
		$.ajax({
			url: UPLOAD_URL,
			data: formData,
			cache: false,
			contentType: false,
			processData: false,
			type: 'POST',
			dataType:"json",
			success: function(resp) {
				if (resp.code == 0) {
					doSend(JSON.stringify(resp), "", MULIT_TYPE.FILE);
				} else {
					showLayer(TEXT.DO_ERROR);
				}
			}, error: function(resp) {
				showLayer(TEXT.DO_ERROR);
			}
		});		
	}
	
	/**
	 */
	function convertBase64UrlToBlob(urlData) {
		var bytes = window.atob(urlData.split(',')[1]); 
		var ab = new ArrayBuffer(bytes.length);
		var ia = new Uint8Array(ab);
		for (var i = 0; i < bytes.length; i++) {
			ia[i] = bytes.charCodeAt(i);
		}
		return new Blob([ab], {
			type: 'image/png'
		});
	}
}

